package com.tanhua.dubbo.api;

import com.tanhua.model.mongo.RecommendUser;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class RecommendUserApiImpl implements RecommendUserApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    //根据toUserId查询Score最高的1个用户
    public RecommendUser queryWithMaxScore(Long toUserId) {
        //1、创建Criteria
        Criteria criteria = Criteria.where("toUserId").is(toUserId);
        //2、创建Query
        Query query = Query.query(criteria)
                            .with(Sort.by(Sort.Order.desc("score"))) //根据score排序
                            .limit(1); //获取1条
        //3、调用MongoTemplate的find或者findOne方法查询
        return mongoTemplate.findOne(query, RecommendUser.class);
    }

    //根据toUserId分页查询
    public List<RecommendUser> queryRecommendUserList(Integer page, Integer pagesize, Long toUserId) {
        //1、创建Criteria
        Criteria criteria = Criteria.where("toUserId").is(toUserId);
        //2、创建Query
        Query query = Query.query(criteria);
        //3、查询总数
        long count = mongoTemplate.count(query, RecommendUser.class);//这一步不是必须的，为了练习
        System.out.println("总条数="+count);
        //4、设置分页参数
        query.with(Sort.by(Sort.Order.desc("score")))
                .skip((page-1) * pagesize)
                .limit(pagesize);
        //5、查询列表
        return mongoTemplate.find(query,RecommendUser.class);
    }

    //根据userId和toUserId查询推荐数据
    public RecommendUser queryByUserId(Long userId, Long toUserId) {
        //1、创建Criteria
        Criteria criteria = Criteria.where("toUserId").is(toUserId).and("userId").is(userId);
        //2、创建Query
        Query query = Query.query(criteria);
        //3、查询
        RecommendUser user = mongoTemplate.findOne(query, RecommendUser.class);
        if(user == null) {
            user = new RecommendUser();
            user.setUserId(userId);
            user.setToUserId(toUserId);
            user.setScore(95d);
        }
        return user;
    }
}
